<template>
    <div class="finance_form_container">
        <el-form ref="financeForm" :rules="rules" :model="formData" label-width="110px"
                 v-enterToNext>
            <el-row>
                <el-col :span="8" v-if="type === 'sale'">
                    <el-form-item label="客户" prop="client_sid">
                        <vSelectBottom v-model="formData.client_sid" type="clientsDrawer"
                                       @event="handleClientEvent" :options="clientOptions"
                                       :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-else>
                    <el-form-item label="供应商" prop="supplier_sid">
                        <vSelectBottom v-model="formData.supplier_sid" type="supplierDrawer"
                                       @event="handleSupplierEvent" :options="supplierOptions"
                                       :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单类型" prop="account_type">
                        <el-select v-model="formData.account_type" placeholder="请选择"
                                   clearable style="width: 100%;" :disabled="!isEditFlag">
                            <el-option v-for="(item, index) in (typeList || [])" :key="index"
                                       :label="item.display_text" :value="item.key3" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单日期" prop="the_date">
                        <el-date-picker v-model="formData.the_date" type="date"
                                        value-format="yyyy-MM-dd"
                                        :disabled="!isEditFlag" style="width: 100%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单号码" prop="code">
                        <el-input v-model="formData.code" autocomplete="off" clearable placeholder="留空则系统自动编码"
                                  :disabled="!isEditFlag"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="资金账号" prop="fund_account_sid">
                        <el-select v-model="formData.fund_account_sid" placeholder="请选择资金账号"
                                   style="width: 100%;" :disabled="!isEditFlag" clearable>
                            <el-option v-for="(item, index) in (baseFundAccountList || [])" :key="index"
                                       :label="item.name" :value="item.sid" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="账单金额" prop="amount">
                        <el-input v-model="formData.amount" autocomplete="off" clearable
                                  :disabled="!isEditFlag" v-double-input="{ len: 4, negative: false }" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="关联单据号码" prop="relation_code">
                        <el-input v-model="formData.relation_code" autocomplete="off" clearable
                                  :disabled="!isEditFlag"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="摘要" prop="note_info">
                        <el-input type="textarea" v-model="formData.note_info" autocomplete="off" clearable
                                  :disabled="!isEditFlag" :row="3" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
export default {
    name: "FinanceForm",
    props: {
        type: {
            type: String,
            default: null,
        },
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
        typeList: {
            type: Array,
            default: null,
        },
    },
    data() {
        return {
            rules: {
                code: [
                    { required: true, message: "请输入账单号码", trigger: "blur" },
                    { max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur", },
                ],
                client_sid: [
                    { required: true, message: "请选择客户", trigger: "change" },
                ],
                supplier_sid: [
                    { required: true, message: "请选择供应商", trigger: "change" },
                ],
                account_type: [
                    { required: true, message: "请选择账单类型", trigger: "change" },
                ],
                the_date: [
                    { required: true, message: "请选择账单日期", trigger: "change" },
                ],
                amount: [
                    { required: true, message: "请输入账单金额", trigger: "blur" },
                ],
            },
            oldCode: '',
            formData: {},
            clientOptions: {
                disabled: false,
                placeholder: '请选择客户',
                bottomAction: {
                    permission: 'save_sys_client',
                    permissionUrl: '/sysClients',
                },
            },
            supplierOptions: {
                disabled: true,
                placeholder: '请选择供应商',
                bottomAction: {
                    permission: 'save_sys_supplier',
                    permissionUrl: '/sysSupplier',
                },
            },
            baseFundAccountList: [],
        };
    },
    computed: {
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            return this.$utils.isEmpty(this.formData.state) || this.formData.state === 0;
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            await _this.getBaseFundAccountList();
            if (!_this.row) {
                return;
            }
            if (_this.$refs.financeForm) {
                _this.$refs.financeForm.clearValidate();
            }
            let sid = _this.$route.query.sid;
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                sid = _this.row.sid;
            }
            if (_this.$utils.isNotEmpty(sid)) {
                await _this.initData(_this.row.sid);
            } else {
                _this.formData = {
                    the_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                };
            }
        },
        initData(sid) {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetJxcFinanceAccountDetailBySid, {
                sid,
            }).then(result => {
                _this.formData = result.data || {};
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        generateCode() {
            const _this = this;
            if (_this.type === 'sale' && _this.$utils.isEmpty(_this.formData.client_sid)) {
                return;
            }
            if (_this.type === 'buy' && _this.$utils.isEmpty(_this.formData.supplier_sid)) {
                return;
            }
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: _this.type === 'sale' ? 'jxc_finance_sale' : 'jxc_finance_buy',
                related_party_sid: _this.formData.client_sid,
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.financeForm) {
                    _this.$refs.financeForm.clearValidate('code');
                }
            });
        },
        handleClientEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    client_sid: event.value,
                });
                if (_this.isEditFlag) {
                    _this.generateCode();
                }
            }
        },
        handleSupplierEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    supplier_sid: event.value,
                });
                if (_this.isEditFlag) {
                    _this.generateCode();
                }
            }
        },
        async getBaseFundAccountList() {
            const _this = this;
            let subData = {nopage: 0};
            await _this.fetchData(_this.$api.API_FindBaseFundAccounts, subData).then((result) => {
                _this.baseFundAccountList = result.data || [];
            }).catch((error) => {
                _this.$message.error(error.message);
            });
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('financeForm');
            if (!valid) {
                return false;
            }
            let subData = $.extend({}, _this.formData);
            subData.type = _this.type;
            return _this.fetchData(_this.$api.API_SaveJxcFinanceAccountDetail, subData).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.finance_form_container {
    width: 100%;
    height: 100%;
}
</style>
